package com.glamour.hlcity.component.framework.registry.impl;

import java.util.Map;


import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;

import org.springframework.core.CollectionFactory;

public class ApplicationContextFactory {

	private static final Map currentContextPerThread = CollectionFactory
			.createConcurrentMapIfPossible(1);

	private ApplicationContextFactory() {
	}

	public static synchronized ApplicationContext getApplicationContext() {
		ClassLoader classLoader = Thread.currentThread()
				.getContextClassLoader();

		if (currentContextPerThread.containsKey(classLoader)) {
			return (ApplicationContext) currentContextPerThread
					.get(classLoader);
		}
		return null;
	}

	public static synchronized void putApplicationContext(
			ApplicationContext context) {
		if (context != null) {
			currentContextPerThread.put(Thread.currentThread()
					.getContextClassLoader(), context);
		}
	}
	
	/**
	 * 获得Bean实例
	 * @param beanName
	 * @return
	 */
	public static Object getBean(String beanName){
		ClassLoader classLoader = Thread.currentThread()
		.getContextClassLoader();
		ApplicationContext context=(ApplicationContext) currentContextPerThread.get(classLoader);
		return context.getBean(beanName);
	}

	/**
	 * 根据变量名对实例进行Bean依赖注入
	 * 
	 * @param obj
	 * @return
	 */
	public static <T> T injectBeansByName(T obj) {
		if (obj == null) {
			throw new IllegalArgumentException(
					"Parameter obj is required for injectSpringBeans."); // NOI18N
		}
		AutowireCapableBeanFactory autowire = getApplicationContext()
				.getAutowireCapableBeanFactory();
		autowire.autowireBeanProperties(obj,
				AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true);
		return obj;
	}

}
